diff --git a/.github/workflows/agent-ci.yml b/.github/workflows/agent-ci.yml new file mode 100644 index 00000000..275b46a8 --- /dev/null +++ b/.github/workflows/agent-ci.yml @@ -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 ./... diff --git a/.github/workflows/agent-release.yml b/.github/workflows/agent-release.yml index 55efbfab..cd9079da 100644 --- a/.github/workflows/agent-release.yml +++ b/.github/workflows/agent-release.yml @@ -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 }} diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml new file mode 100644 index 00000000..dfa5edd5 --- /dev/null +++ b/.github/workflows/backend-ci.yml @@ -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 diff --git a/.gitignore b/.gitignore index e52b43c8..f6f1618e 100644 --- a/.gitignore +++ b/.gitignore @@ -128,3 +128,5 @@ docs/PLAN_AGENT_FLEET.md /.claude /.github/skills /.playwright-mcp +docs/UI_CONSISTENCY_AUDIT.md +docs/REMOTE_ACCESS_ROADMAP.md diff --git a/SECURITY.md b/SECURITY.md index 624b613d..1bbecb3b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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 diff --git a/VERSION b/VERSION index 1df3b822..5f3f7155 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.6.10 +1.6.17 diff --git a/agent/Makefile b/agent/Makefile index 94a74d76..8eb98fb4 100644 --- a/agent/Makefile +++ b/agent/Makefile @@ -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 diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go index d14ed27d..062465be 100644 --- a/agent/cmd/agent/main.go +++ b/agent/cmd/agent/main.go @@ -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//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") diff --git a/agent/go.mod b/agent/go.mod index 48563e98..740d59a2 100644 --- a/agent/go.mod +++ b/agent/go.mod @@ -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 ) diff --git a/agent/go.sum b/agent/go.sum index c771112f..982b5fb8 100644 --- a/agent/go.sum +++ b/agent/go.sum @@ -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= diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go index f292b6c2..857e3478 100644 --- a/agent/internal/agent/agent.go +++ b/agent/internal/agent/agent.go @@ -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) diff --git a/agent/internal/agent/firewall_handlers.go b/agent/internal/agent/firewall_handlers.go new file mode 100644 index 00000000..10a9fda3 --- /dev/null +++ b/agent/internal/agent/firewall_handlers.go @@ -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)") +} diff --git a/agent/internal/agent/wireguard_handlers.go b/agent/internal/agent/wireguard_handlers.go new file mode 100644 index 00000000..e98aa5a8 --- /dev/null +++ b/agent/internal/agent/wireguard_handlers.go @@ -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 +} diff --git a/agent/internal/agentui/platform_other.go b/agent/internal/agentui/platform_other.go index 8a26086b..efffd4e0 100644 --- a/agent/internal/agentui/platform_other.go +++ b/agent/internal/agentui/platform_other.go @@ -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") } diff --git a/agent/internal/capabilities/capabilities.go b/agent/internal/capabilities/capabilities.go index 7d7e142c..755f73eb 100644 --- a/agent/internal/capabilities/capabilities.go +++ b/agent/internal/capabilities/capabilities.go @@ -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 " --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 diff --git a/agent/internal/docker/client.go b/agent/internal/docker/client.go index b546ecec..ff99c18c 100644 --- a/agent/internal/docker/client.go +++ b/agent/internal/docker/client.go @@ -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") diff --git a/agent/internal/updater/updater.go b/agent/internal/updater/updater.go index ab7cacd3..21cc3c1d 100644 --- a/agent/internal/updater/updater.go +++ b/agent/internal/updater/updater.go @@ -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) { diff --git a/agent/internal/updater/updater_test.go b/agent/internal/updater/updater_test.go new file mode 100644 index 00000000..181ee8eb --- /dev/null +++ b/agent/internal/updater/updater_test.go @@ -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) + } +} diff --git a/agent/internal/wireguard/wireguard.go b/agent/internal/wireguard/wireguard.go new file mode 100644 index 00000000..78a3d992 --- /dev/null +++ b/agent/internal/wireguard/wireguard.go @@ -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 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 +} diff --git a/agent/internal/wireguard/wireguard_dump_linux_test.go b/agent/internal/wireguard/wireguard_dump_linux_test.go new file mode 100644 index 00000000..94586ecf --- /dev/null +++ b/agent/internal/wireguard/wireguard_dump_linux_test.go @@ -0,0 +1,63 @@ +//go:build linux + +package wireguard + +import "testing" + +// TestParseWgDump checks the `wg show 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) + } +} diff --git a/agent/internal/wireguard/wireguard_linux.go b/agent/internal/wireguard/wireguard_linux.go new file mode 100644 index 00000000..27aee77e --- /dev/null +++ b/agent/internal/wireguard/wireguard_linux.go @@ -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 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 +} diff --git a/agent/internal/wireguard/wireguard_other.go b/agent/internal/wireguard/wireguard_other.go new file mode 100644 index 00000000..c46f0bc7 --- /dev/null +++ b/agent/internal/wireguard/wireguard_other.go @@ -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 +} diff --git a/agent/internal/wireguard/wireguard_test.go b/agent/internal/wireguard/wireguard_test.go new file mode 100644 index 00000000..72dc95b1 --- /dev/null +++ b/agent/internal/wireguard/wireguard_test.go @@ -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) + } +} diff --git a/agent/internal/wireguard/wireguard_userspace_test.go b/agent/internal/wireguard/wireguard_userspace_test.go new file mode 100644 index 00000000..6da68c92 --- /dev/null +++ b/agent/internal/wireguard/wireguard_userspace_test.go @@ -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") + } +} diff --git a/agent/packaging/deb/build.sh b/agent/packaging/deb/build.sh index 8c78994c..4faad166 100644 --- a/agent/packaging/deb/build.sh +++ b/agent/packaging/deb/build.sh @@ -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" diff --git a/agent/packaging/rpm/build.sh b/agent/packaging/rpm/build.sh index 939634ed..e1196a3f 100644 --- a/agent/packaging/rpm/build.sh +++ b/agent/packaging/rpm/build.sh @@ -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" diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.go index d029bba4..ae254bf6 100644 --- a/agent/pkg/protocol/messages.go +++ b/agent/pkg/protocol/messages.go @@ -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 diff --git a/agent/scripts/install.ps1 b/agent/scripts/install.ps1 index 9bdba718..f3cf5e10 100644 --- a/agent/scripts/install.ps1 +++ b/agent/scripts/install.ps1 @@ -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" diff --git a/agent/scripts/install.sh b/agent/scripts/install.sh index 6dd4f97a..f3569d3e 100644 --- a/agent/scripts/install.sh +++ b/agent/scripts/install.sh @@ -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 ` +# 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//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 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index ae1b80ce..69338b63 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -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 diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.py index 00027dba..1426d006 100644 --- a/backend/app/agent_gateway.py +++ b/backend/app/agent_gateway.py @@ -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). diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index bc8b6b2b..143eeb2d 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -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 # ============================================ diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py index ad9e0a97..847bf70c 100644 --- a/backend/app/api/apps.py +++ b/backend/app/api/apps.py @@ -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 diff --git a/backend/app/api/connections.py b/backend/app/api/connections.py new file mode 100644 index 00000000..c64e4133 --- /dev/null +++ b/backend/app/api/connections.py @@ -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)}) diff --git a/backend/app/api/databases.py b/backend/app/api/databases.py index b795fdad..fe081821 100644 --- a/backend/app/api/databases.py +++ b/backend/app/api/databases.py @@ -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///query', methods=['POST']) diff --git a/backend/app/api/domains.py b/backend/app/api/domains.py index 1a2beed6..048c937f 100644 --- a/backend/app/api/domains.py +++ b/backend/app/api/domains.py @@ -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] diff --git a/backend/app/api/email.py b/backend/app/api/email.py index 57b9e7d4..b969dc8a 100644 --- a/backend/app/api/email.py +++ b/backend/app/api/email.py @@ -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']) diff --git a/backend/app/api/files.py b/backend/app/api/files.py index cfc01085..d8579b6a 100644 --- a/backend/app/api/files.py +++ b/backend/app/api/files.py @@ -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 diff --git a/backend/app/api/pairing.py b/backend/app/api/pairing.py index f1248b10..b01d20fe 100644 --- a/backend/app/api/pairing.py +++ b/backend/app/api/pairing.py @@ -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()) diff --git a/backend/app/api/registrars.py b/backend/app/api/registrars.py new file mode 100644 index 00000000..0175153e --- /dev/null +++ b/backend/app/api/registrars.py @@ -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/', 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//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()}) diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index 753da23d..efb907bd 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -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('//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: diff --git a/backend/app/api/source_connections.py b/backend/app/api/source_connections.py index 2d823589..2b1588bf 100644 --- a/backend/app/api/source_connections.py +++ b/backend/app/api/source_connections.py @@ -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//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//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) diff --git a/backend/app/api/tunnels.py b/backend/app/api/tunnels.py new file mode 100644 index 00000000..7b58c7c0 --- /dev/null +++ b/backend/app/api/tunnels.py @@ -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('/', 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('/', 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('//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('//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('//services/', 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}) diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py index e8d25250..c25e69d1 100644 --- a/backend/app/api/wordpress.py +++ b/backend/app/api/wordpress.py @@ -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//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//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//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//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//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 diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.py index fcc55a56..c9185876 100644 --- a/backend/app/api/workspaces.py +++ b/backend/app/api/workspaces.py @@ -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('/', methods=['GET']) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 1daba4e7..9d0e6f18 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/email.py b/backend/app/models/email.py index 2cbcd36a..41a1a961 100644 --- a/backend/app/models/email.py +++ b/backend/app/models/email.py @@ -169,3 +169,35 @@ class DNSProviderConfig(db.Model): def __repr__(self): return f'' + + +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'' diff --git a/backend/app/models/exposed_service.py b/backend/app/models/exposed_service.py new file mode 100644 index 00000000..c9950d92 --- /dev/null +++ b/backend/app/models/exposed_service.py @@ -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 ' tunnel %s :%s>' % (self.hostname, self.tunnel_id, self.port) diff --git a/backend/app/models/registrar_connection.py b/backend/app/models/registrar_connection.py new file mode 100644 index 00000000..1f71ce5f --- /dev/null +++ b/backend/app/models/registrar_connection.py @@ -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'' diff --git a/backend/app/models/source_connection.py b/backend/app/models/source_connection.py index 48566e2d..a944bb2b 100644 --- a/backend/app/models/source_connection.py +++ b/backend/app/models/source_connection.py @@ -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' diff --git a/backend/app/models/tunnel.py b/backend/app/models/tunnel.py new file mode 100644 index 00000000..4e1fd0b4 --- /dev/null +++ b/backend/app/models/tunnel.py @@ -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 '%s>' % (self.interface_name, self.edge_server_id, self.private_server_id) diff --git a/backend/app/services/advanced_ssl_service.py b/backend/app/services/advanced_ssl_service.py index 5a0de41d..f418a03d 100644 --- a/backend/app/services/advanced_ssl_service.py +++ b/backend/app/services/advanced_ssl_service.py @@ -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)} diff --git a/backend/app/services/agent_plugin_service.py b/backend/app/services/agent_plugin_service.py index 6bd44d6c..b4aef1d4 100644 --- a/backend/app/services/agent_plugin_service.py +++ b/backend/app/services/agent_plugin_service.py @@ -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 diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py index a074848f..640556f0 100644 --- a/backend/app/services/agent_registry.py +++ b/backend/app/services/agent_registry.py @@ -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 diff --git a/backend/app/services/cloud_provisioning_service.py b/backend/app/services/cloud_provisioning_service.py index 2813116e..4ab68edb 100644 --- a/backend/app/services/cloud_provisioning_service.py +++ b/backend/app/services/cloud_provisioning_service.py @@ -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', } diff --git a/backend/app/services/connection_registry.py b/backend/app/services/connection_registry.py new file mode 100644 index 00000000..08ff659b --- /dev/null +++ b/backend/app/services/connection_registry.py @@ -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 [] diff --git a/backend/app/services/database_service.py b/backend/app/services/database_service.py index 76819bb0..af45e828 100644 --- a/backend/app/services/database_service.py +++ b/backend/app/services/database_service.py @@ -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, diff --git a/backend/app/services/dns_provider_service.py b/backend/app/services/dns_provider_service.py index 5e51d7b6..f25ddf9a 100644 --- a/backend/app/services/dns_provider_service.py +++ b/backend/app/services/dns_provider_service.py @@ -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 " "; 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 " "; 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)} diff --git a/backend/app/services/email_relay_service.py b/backend/app/services/email_relay_service.py new file mode 100644 index 00000000..5545f164 --- /dev/null +++ b/backend/app/services/email_relay_service.py @@ -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)} diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.py index 3d2d693e..20295bbd 100644 --- a/backend/app/services/nginx_service.py +++ b/backend/app/services/nginx_service.py @@ -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.""" diff --git a/backend/app/services/postfix_service.py b/backend/app/services/postfix_service.py index f690ddd9..ebbc9ce4 100644 --- a/backend/app/services/postfix_service.py +++ b/backend/app/services/postfix_service.py @@ -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)} diff --git a/backend/app/services/registrar_service.py b/backend/app/services/registrar_service.py new file mode 100644 index 00000000..e42f38bf --- /dev/null +++ b/backend/app/services/registrar_service.py @@ -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 [], + } diff --git a/backend/app/services/server_template_service.py b/backend/app/services/server_template_service.py index b034ae9f..f3d1e68a 100644 --- a/backend/app/services/server_template_service.py +++ b/backend/app/services/server_template_service.py @@ -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 diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.py index 8e47adf2..e33a48cc 100644 --- a/backend/app/services/settings_service.py +++ b/backend/app/services/settings_service.py @@ -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 .. Point a wildcard DNS record (*.) 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'}, diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py new file mode 100644 index 00000000..10f9ea06 --- /dev/null +++ b/backend/app/services/site_domain_service.py @@ -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 ``.`` and the operator points a single wildcard DNS +record (``*.``) 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:`` 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): + """``.`` 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}' diff --git a/backend/app/services/sites_https_service.py b/backend/app/services/sites_https_service.py new file mode 100644 index 00000000..16f3874e --- /dev/null +++ b/backend/app/services/sites_https_service.py @@ -0,0 +1,69 @@ +"""One-time setup that makes managed subdomains HTTPS. + +Creates the wildcard DNS record (``*.``) 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 ``*.`` + ```` 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} diff --git a/backend/app/services/source_connection_service.py b/backend/app/services/source_connection_service.py index 811d5741..8364117b 100644 --- a/backend/app/services/source_connection_service.py +++ b/backend/app/services/source_connection_service.py @@ -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('/') diff --git a/backend/app/services/storage_provider_service.py b/backend/app/services/storage_provider_service.py index 2942c006..9d7931e8 100644 --- a/backend/app/services/storage_provider_service.py +++ b/backend/app/services/storage_provider_service.py @@ -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 diff --git a/backend/app/services/tunnel_broker_service.py b/backend/app/services/tunnel_broker_service.py new file mode 100644 index 00000000..410d5689 --- /dev/null +++ b/backend/app/services/tunnel_broker_service.py @@ -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 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, + ], + } diff --git a/backend/app/services/tunnel_netutil.py b/backend/app/services/tunnel_netutil.py new file mode 100644 index 00000000..048b4152 --- /dev/null +++ b/backend/app/services/tunnel_netutil.py @@ -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.")} diff --git a/backend/app/services/tunnel_publish_service.py b/backend/app/services/tunnel_publish_service.py new file mode 100644 index 00000000..947715a7 --- /dev/null +++ b/backend/app/services/tunnel_publish_service.py @@ -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}(? → the private service on . 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 diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py index 7b76c635..839fbf01 100644 --- a/backend/app/services/wordpress_service.py +++ b/backend/app/services/wordpress_service.py @@ -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 (.) instead of + # localhost:. 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 . 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: 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) diff --git a/backend/app/services/workspace_service.py b/backend/app/services/workspace_service.py index aebb35e9..a3ccb1b2 100644 --- a/backend/app/services/workspace_service.py +++ b/backend/app/services/workspace_service.py @@ -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 diff --git a/backend/app/services/wp_analytics_service.py b/backend/app/services/wp_analytics_service.py index 1c1427a3..3e89ebdf 100644 --- a/backend/app/services/wp_analytics_service.py +++ b/backend/app/services/wp_analytics_service.py @@ -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: " + _PHP_ERR_RE = re.compile(r'^\[(?P