diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..45c7e6f --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,16 @@ +name: Test +on: + pull_request: + push: + branches: [main, dev] +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + - run: go test -race ./... diff --git a/README.md b/README.md index 40ffaeb..9230554 100644 --- a/README.md +++ b/README.md @@ -28,3 +28,21 @@ Minimal HTTPS control API rewritten from the original bash script. Uses only the - `POST /node/geofiles` with JSON `{"region":"iran|russia|china"}` → runs `pg-node geofiles --` - `POST /node/hard_reset` → runs `pg-node restart` (60 s timeout) + +## TLS and private backends + +`TLS_ENABLED` defaults to `true` and invalid boolean values fail startup. +Both node services use `NODE_HOST`, `SSL_CERT_FILE`, and `SSL_KEY_FILE` from the +same environment file. A missing `NODE_HOST` binds to `0.0.0.0` with TLS. + +For an external TLS web server, set `TLS_ENABLED=false`; certificates are then +unnecessary and the default bind address is `127.0.0.1`. Explicit bindings must +be literal IPv4 loopback, `::1`, RFC1918 IPv4, or IPv6 unique-local addresses. +IPv4-mapped IPv6 addresses are normalized. Public, wildcard, link-local, +multicast, scoped, and malformed addresses fail startup. API-key authentication +remains required. The panel always connects to the web server over HTTPS. + +Use the same frontend certificate on the node and maintenance ports when pinned. +Do not expose private backend ports through firewall/NAT/container publishing. +See the node repository's `docs/node-tls.md` and `examples/nginx/` for deployment +examples, renewal behavior and rollback instructions. diff --git a/config.go b/config.go index 6d83b5d..df75d3d 100644 --- a/config.go +++ b/config.go @@ -6,8 +6,11 @@ import ( "encoding/pem" "errors" "fmt" + "net/netip" "os" "path/filepath" + "strconv" + "strings" "time" "github.com/joho/godotenv" @@ -22,12 +25,14 @@ const ( ) type config struct { - AppName string - APIPort string - APIKey string - SSLCert string - SSLKey string - EnvFile string + TLSEnabled bool + NodeHost string + AppName string + APIPort string + APIKey string + SSLCert string + SSLKey string + EnvFile string } type certInfo struct { @@ -101,8 +106,9 @@ func checkCertificate(certPath string) (*certInfo, error) { func loadConfig() (config, error) { cfg := config{ - AppName: defaultAppName, - APIPort: defaultAPIPort, + AppName: defaultAppName, + TLSEnabled: true, + APIPort: defaultAPIPort, } envFile, fallbackUsed := determineEnvFile() @@ -134,6 +140,38 @@ func loadConfig() (config, error) { if cfg.APIKey == "" { return cfg, errors.New("API_KEY must be set in the env file") } + if value, exists := os.LookupEnv("TLS_ENABLED"); exists { + var err error + cfg.TLSEnabled, err = strconv.ParseBool(value) + if err != nil { + return cfg, fmt.Errorf("invalid TLS_ENABLED %q: expected a boolean", value) + } + } + cfg.NodeHost = "0.0.0.0" + if !cfg.TLSEnabled { + cfg.NodeHost = "127.0.0.1" + } + if host, exists := os.LookupEnv("NODE_HOST"); exists { + cfg.NodeHost = strings.TrimSpace(host) + } + addr, err := netip.ParseAddr(cfg.NodeHost) + if !cfg.TLSEnabled { + if err != nil || addr.Zone() != "" { + return cfg, fmt.Errorf("invalid private NODE_HOST %q", cfg.NodeHost) + } + addr = addr.Unmap() + if !addr.IsLoopback() && !addr.IsPrivate() { + return cfg, fmt.Errorf("TLS_ENABLED=false requires a private NODE_HOST, got %q", cfg.NodeHost) + } + cfg.NodeHost = addr.String() + return cfg, nil + } + if strings.EqualFold(cfg.NodeHost, "localhost") { + cfg.NodeHost = "127.0.0.1" + } else if err != nil { + logf("Invalid NODE_HOST %q; using 127.0.0.1", cfg.NodeHost) + cfg.NodeHost = "127.0.0.1" + } if cfg.SSLCert == "" || cfg.SSLKey == "" { return cfg, errors.New("TLS required: set SSL_CERT_FILE and SSL_KEY_FILE in the env file") } diff --git a/config_test.go b/config_test.go new file mode 100644 index 0000000..3e51d02 --- /dev/null +++ b/config_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestTLSBackendConfiguration(t *testing.T) { + t.Setenv("ENV_FILE", filepath.Join(t.TempDir(), "absent.env")) + t.Setenv("API_KEY", "test-key") + t.Setenv("SSL_CERT_FILE", "/does/not/exist") + t.Setenv("SSL_KEY_FILE", "/does/not/exist") + t.Setenv("TLS_ENABLED", "false") + t.Setenv("NODE_HOST", "127.0.0.1") + os.Unsetenv("NODE_HOST") + cfg, err := loadConfig() + if err != nil || cfg.NodeHost != "127.0.0.1" || cfg.TLSEnabled { + t.Fatalf("backend defaults: %+v %v", cfg, err) + } + for _, host := range []string{"127.0.0.2", "::1", "10.1.2.3", "172.16.1.1", "192.168.1.1", "fd00::1", "::ffff:192.168.1.1"} { + t.Setenv("NODE_HOST", host) + if _, err := loadConfig(); err != nil { + t.Errorf("rejected %s: %v", host, err) + } + } + for _, host := range []string{"", "localhost", "invalid", "0.0.0.0", "::", "8.8.8.8", "169.254.1.1", "100.64.0.1", "192.0.2.1", "224.0.0.1", "fe80::1", "2001:db8::1", "ff02::1", "::ffff:8.8.8.8", "fd00::1%eth0"} { + t.Setenv("NODE_HOST", host) + if _, err := loadConfig(); err == nil { + t.Errorf("accepted unsafe %s", host) + } + } + t.Setenv("NODE_HOST", "127.0.0.1") + for _, value := range []string{"", "no", "disabled"} { + t.Setenv("TLS_ENABLED", value) + if _, err := loadConfig(); err == nil { + t.Errorf("accepted invalid TLS_ENABLED=%q", value) + } + } + t.Setenv("TLS_ENABLED", "true") + if _, err := loadConfig(); err == nil { + t.Fatal("TLS must still require certificate files") + } + os.Unsetenv("TLS_ENABLED") + if cfg, err := loadConfig(); !cfg.TLSEnabled || err == nil { + t.Fatal("missing TLS_ENABLED must require TLS") + } +} diff --git a/main.go b/main.go index 1ee2a71..0cdabe9 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,9 @@ package main import ( + "crypto/tls" "errors" + "net" "net/http" "os" "time" @@ -14,36 +16,41 @@ func main() { os.Exit(1) } - tlsConfig, err := LoadTLSCredentials(cfg.SSLCert, cfg.SSLKey) - if err != nil { - logf("failed to load TLS credentials: %v", err) - os.Exit(1) - } - - info, err := checkCertificate(cfg.SSLCert) - if err != nil { - logf("Certificate validation failed for %s: %v", cfg.SSLCert, err) - } else { - switch { - case info.SelfSigned: - logf("Certificate is self-signed: %s", cfg.SSLCert) - default: - logf("Certificate appears to be CA-signed: %s", cfg.SSLCert) + var tlsConfig *tls.Config + if cfg.TLSEnabled { + tlsConfig, err = LoadTLSCredentials(cfg.SSLCert, cfg.SSLKey) + if err != nil { + logf("failed to load TLS credentials: %v", err) + os.Exit(1) } - if !info.NotAfter.IsZero() { - now := time.Now() - if now.After(info.NotAfter) { - logf("Warning: Certificate has expired: %s", cfg.SSLCert) - logf("Expiration: %s", info.NotAfter.Format(time.RFC3339)) - } else { - days := int(info.NotAfter.Sub(now).Hours() / 24) - logf("Certificate valid for %d more days (expires: %s)", days, info.NotAfter.Format(time.RFC3339)) + info, err := checkCertificate(cfg.SSLCert) + if err != nil { + logf("Certificate validation failed for %s: %v", cfg.SSLCert, err) + } else { + switch { + case info.SelfSigned: + logf("Certificate is self-signed: %s", cfg.SSLCert) + default: + logf("Certificate appears to be CA-signed: %s", cfg.SSLCert) + } + + if !info.NotAfter.IsZero() { + now := time.Now() + if now.After(info.NotAfter) { + logf("Warning: Certificate has expired: %s", cfg.SSLCert) + logf("Expiration: %s", info.NotAfter.Format(time.RFC3339)) + } else { + days := int(info.NotAfter.Sub(now).Hours() / 24) + logf("Certificate valid for %d more days (expires: %s)", days, info.NotAfter.Format(time.RFC3339)) + } } } - } - logf("TLS enabled on port %s with cert=%s key=%s", cfg.APIPort, cfg.SSLCert, cfg.SSLKey) + logf("TLS enabled on port %s with cert=%s key=%s", cfg.APIPort, cfg.SSLCert, cfg.SSLKey) + } else { + logf("External TLS backend on %s:%s", cfg.NodeHost, cfg.APIPort) + } logf("API key protection enabled") logf("node app (hard reset target): %s", cfg.AppName) @@ -56,15 +63,20 @@ func main() { mux.HandleFunc("POST /node/hard_reset", s.handleHardReset) httpServer := &http.Server{ - Addr: ":" + cfg.APIPort, + Addr: net.JoinHostPort(cfg.NodeHost, cfg.APIPort), Handler: mux, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, TLSConfig: tlsConfig, } - logf("node-serviced listening on https://localhost:%s", cfg.APIPort) - if err := httpServer.ListenAndServeTLS("", ""); err != nil && !errors.Is(err, http.ErrServerClosed) { + var serveErr error + if cfg.TLSEnabled { + serveErr = httpServer.ListenAndServeTLS("", "") + } else { + serveErr = httpServer.ListenAndServe() + } + if err := serveErr; err != nil && !errors.Is(err, http.ErrServerClosed) { logf("server error: %v", err) os.Exit(1) } diff --git a/transport_test.go b/transport_test.go new file mode 100644 index 0000000..87868fd --- /dev/null +++ b/transport_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "fmt" + "math/big" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func TestMaintenanceProcess(t *testing.T) { + if os.Getenv("NODE_SERVICE_TEST_PROCESS") == "1" { + main() + } +} + +func TestMaintenanceTransports(t *testing.T) { + for _, enabled := range []bool{true, false} { + t.Run(fmt.Sprintf("TLS=%v", enabled), func(t *testing.T) { + dir := t.TempDir() + certPath, keyPath := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem") + pool := x509.NewCertPool() + if enabled { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test"}, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(certPath, certPEM, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0600); err != nil { + t.Fatal(err) + } + pool.AppendCertsFromPEM(certPEM) + } + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + l.Close() + _, port, _ := net.SplitHostPort(addr) + envPath := filepath.Join(dir, ".env") + data := fmt.Sprintf("API_KEY=test-key\nAPI_PORT=%s\nNODE_HOST=127.0.0.1\nTLS_ENABLED=%v\nSSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\n", port, enabled, certPath, keyPath) + if err := os.WriteFile(envPath, []byte(data), 0600); err != nil { + t.Fatal(err) + } + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(exe, "-test.run=^TestMaintenanceProcess$") + cmd.Env = append(os.Environ(), "NODE_SERVICE_TEST_PROCESS=1", "ENV_FILE="+envPath) + logfile, err := os.Create(filepath.Join(dir, "service.log")) + if err != nil { + t.Fatal(err) + } + defer logfile.Close() + cmd.Stdout, cmd.Stderr = logfile, logfile + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) + scheme := "http" + if enabled { + scheme = "https" + } + client := &http.Client{Timeout: time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}} + defer client.CloseIdleConnections() + url := scheme + "://" + addr + "/" + deadline := time.Now().Add(5 * time.Second) + for { + resp, err := client.Get(url) + if err == nil { + resp.Body.Close() + if resp.StatusCode != 401 { + t.Fatalf("missing API key: %d", resp.StatusCode) + } + break + } + if time.Now().After(deadline) { + data, _ := os.ReadFile(logfile.Name()) + t.Fatalf("startup: %v\n%s", err, data) + } + time.Sleep(20 * time.Millisecond) + } + req, _ := http.NewRequest("GET", url, nil) + req.Header.Set("x-api-key", "test-key") + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != 200 { + t.Fatalf("authenticated maintenance: %d", resp.StatusCode) + } + }) + } +}