A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): check dns, tls, origin, proxy, client ip and voice
Hampusb6074918ece7
diff --git a/fluxer_rexctl/internal/checks/app_proxy.go b/fluxer_rexctl/internal/checks/app_proxy.gonew file mode 100644index 000000000..f8fe1af62--- /dev/null+++ b/fluxer_rexctl/internal/checks/app_proxy.go@@ -0,0 +1,35 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "strings"+)++func init() {+ Register(Check{ID: "app-proxy-discovery", Phases: Installed, Run: runAppProxy, Fix: fixAppProxy, SafeFix: true})+}++func runAppProxy(ctx context.Context, e *Env) Result {+ if e.Instance == nil || !e.running(ctx, "edge") || !e.running(ctx, "app-proxy") {+ return skip("")+ }+ out, err := e.exec(ctx, "edge", "", "wget", "-q", "-O", "/dev/null", "http://app-proxy:8080/")+ if err == nil {+ return pass("The web app loads.")+ }+ r := fixable(fail("The web app isn't loading.", "Run rexctl doctor --fix to restart it."))+ if strings.Contains(out, "503") {+ r.Message = "The web app shows an error page."+ }+ r.Details = []string{out}+ return r+}++func fixAppProxy(ctx context.Context, e *Env) error {+ if e.Project == nil {+ return errNoProject+ }+ return e.Project.Restart(ctx, "app-proxy")+}diff --git a/fluxer_rexctl/internal/checks/certificate.go b/fluxer_rexctl/internal/checks/certificate.gonew file mode 100644index 000000000..c0e8ab59a--- /dev/null+++ b/fluxer_rexctl/internal/checks/certificate.go@@ -0,0 +1,52 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "crypto/tls"+ "errors"+ "fmt"+ "net"+ "strings"+ "time"+)++func init() {+ Register(Check{ID: "certificate", Phases: Installed, Run: runCertificate})+}++func runCertificate(ctx context.Context, e *Env) Result {+ if e.Instance == nil || e.mode() != modeBundled || privateDomain(e.Domain) {+ return skip("")+ }+ if strings.EqualFold(e.value("FLUXER_PUBLIC_SCHEME"), "http") || strings.EqualFold(e.value("FLUXER_EDGE_TLS"), "internal") {+ return skip("")+ }+ d := tls.Dialer{+ NetDialer: &net.Dialer{Timeout: 10 * time.Second},+ Config: &tls.Config{ServerName: e.Domain},+ }+ dialCtx, cancel := context.WithTimeout(ctx, 15*time.Second)+ defer cancel()+ conn, err := d.DialContext(dialCtx, "tcp", e.localAddr("FLUXER_HTTPS_PORT", "443"))+ if err != nil {+ var opErr *net.OpError+ if errors.As(err, &opErr) && opErr.Op == "dial" {+ return skip("")+ }+ return fail(fmt.Sprintf("Couldn't get a certificate for %s.", e.Domain),+ "Open ports 80 and 443 in your hosting provider's firewall, then run rexctl doctor.")+ }+ defer conn.Close()+ certs := conn.(*tls.Conn).ConnectionState().PeerCertificates+ if len(certs) == 0 {+ return skip("")+ }+ expires := certs[0].NotAfter+ if time.Until(expires) < 14*24*time.Hour {+ return warn(fmt.Sprintf("The certificate for %s expires on %s.", e.Domain, day(expires)),+ "Run rexctl logs edge to see why it hasn't renewed.")+ }+ return pass(fmt.Sprintf("The certificate for %s is valid until %s.", e.Domain, day(expires)))+}diff --git a/fluxer_rexctl/internal/checks/client_ip.go b/fluxer_rexctl/internal/checks/client_ip.gonew file mode 100644index 000000000..1944b519c--- /dev/null+++ b/fluxer_rexctl/internal/checks/client_ip.go@@ -0,0 +1,70 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "fmt"+ "net/http"+ "time"+)++const (+ clientIPWindow = 7 * 24 * time.Hour+ clientIPMinimum = 3+)++func init() {+ Register(Check{ID: "client-ip", Phases: Installed, Run: runClientIP})+}++type clientIPUser struct {+ LastActiveAt *time.Time `json:"last_active_at"`+ LastActiveIP *string `json:"last_active_ip"`+}++func runClientIP(ctx context.Context, e *Env) Result {+ if e.Admin == nil || !e.running(ctx, "api") {+ return skip("")+ }+ var resp struct {+ Users []clientIPUser `json:"users"`+ }+ if err := e.Admin.Call(ctx, http.MethodGet, "/admin/users", map[string]string{"limit": "100"}, nil, &resp); err != nil {+ return skip("")+ }+ ip, n := sharedIP(resp.Users, time.Now())+ if n < clientIPMinimum {+ return skip("")+ }+ if ip == "" {+ return pass("People who use your instance show their own IP addresses.")+ }+ fix := "Turn on IPv6 for Docker on this machine, then run rexctl restart."+ if e.mode() != modeBundled {+ fix = "Make your proxy set the X-Forwarded-For header, then run rexctl doctor."+ }+ return warn(fmt.Sprintf("Everyone who used your instance this week has the IP address %s.", ip), fix)+}++func sharedIP(users []clientIPUser, now time.Time) (string, int) {+ var ips []string+ for _, u := range users {+ if u.LastActiveAt == nil || u.LastActiveIP == nil || *u.LastActiveIP == "" {+ continue+ }+ if now.Sub(*u.LastActiveAt) > clientIPWindow {+ continue+ }+ ips = append(ips, *u.LastActiveIP)+ }+ if len(ips) == 0 {+ return "", 0+ }+ for _, ip := range ips[1:] {+ if ip != ips[0] {+ return "", len(ips)+ }+ }+ return ips[0], len(ips)+}diff --git a/fluxer_rexctl/internal/checks/discovery.go b/fluxer_rexctl/internal/checks/discovery.gonew file mode 100644index 000000000..2ad830e1d--- /dev/null+++ b/fluxer_rexctl/internal/checks/discovery.go@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "encoding/json"+ "fmt"+ "net/url"+ "strings"+)++func init() {+ Register(Check{ID: "discovery", Phases: Installed, Run: runDiscovery, Fix: fixDiscovery, SafeFix: true})+}++type discoveryDoc struct {+ Endpoints struct {+ API string `json:"api"`+ WebApp string `json:"webapp"`+ } `json:"endpoints"`+}++func runDiscovery(ctx context.Context, e *Env) Result {+ if e.Instance == nil || e.Domain == "" || !e.running(ctx, "edge") || !e.running(ctx, "api") {+ return skip("")+ }+ out, err := e.exec(ctx, "edge", "", "wget", "-q", "-O", "-", "http://127.0.0.1:8088/.well-known/fluxer")+ if err != nil {+ r := fail("Apps can't load your instance's details.", "Run rexctl logs api to see why.")+ r.Details = []string{out}+ return r+ }+ var doc discoveryDoc+ start := strings.Index(out, "{")+ if start < 0 || json.Unmarshal([]byte(out[start:]), &doc) != nil {+ return fail("Apps can't load your instance's details.", "Run rexctl logs api to see why.")+ }+ got := endpointHost(doc.Endpoints.API)+ if got == "" {+ got = endpointHost(doc.Endpoints.WebApp)+ }+ if got != "" && !strings.EqualFold(got, e.Domain) {+ return fixable(fail(fmt.Sprintf("Apps are told to connect to %s and your instance is %s.", got, e.Domain),+ "Run rexctl doctor --fix to apply your instance's address."))+ }+ return pass(fmt.Sprintf("Apps are told to connect to %s.", e.Domain))+}++func endpointHost(s string) string {+ u, err := url.Parse(strings.TrimSpace(s))+ if err != nil {+ return ""+ }+ return u.Hostname()+}++func fixDiscovery(ctx context.Context, e *Env) error { return e.up(ctx) }diff --git a/fluxer_rexctl/internal/checks/dns.go b/fluxer_rexctl/internal/checks/dns.gonew file mode 100644index 000000000..5241d8159--- /dev/null+++ b/fluxer_rexctl/internal/checks/dns.go@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "errors"+ "fmt"+ "net"+ "time"+)++func init() {+ Register(Check{ID: "dns", Phases: Preinstall | Installed, Run: runDNS})+}++func runDNS(ctx context.Context, e *Env) Result {+ if privateDomain(e.Domain) {+ return skip("")+ }+ lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ addrs, err := net.DefaultResolver.LookupIPAddr(lookupCtx, e.Domain)+ var dnsErr *net.DNSError+ if err != nil && !(errors.As(err, &dnsErr) && dnsErr.IsNotFound) {+ return skip(fmt.Sprintf("Couldn't look up %s.", e.Domain))+ }+ if e.mode() != modeBundled {+ if len(addrs) == 0 {+ return fail(fmt.Sprintf("%s doesn't point anywhere yet.", e.Domain),+ "Add a DNS record for it that points to your proxy, then run rexctl doctor.")+ }+ return pass(fmt.Sprintf("%s points to %s.", e.Domain, addrs[0].IP))+ }+ public, perr := e.publicAddress(ctx)+ if len(addrs) == 0 {+ if perr != nil {+ return fail(fmt.Sprintf("%s doesn't point to this machine yet.", e.Domain),+ "Add an A record for it pointing to this machine's public IP address, then run rexctl doctor.")+ }+ return fail(fmt.Sprintf("%s doesn't point to this machine yet.", e.Domain),+ fmt.Sprintf("Add an A record for it pointing to %s, then run rexctl doctor.", public))+ }+ if pointsHere(addrs, public) {+ shown := public+ if shown == "" {+ shown = addrs[0].IP.String()+ }+ return pass(fmt.Sprintf("%s points to this machine (%s).", e.Domain, shown))+ }+ if perr != nil {+ return skip(fmt.Sprintf("Couldn't find this machine's public IP address to compare with %s.", e.Domain))+ }+ return fail(fmt.Sprintf("%s points to %s and this machine is %s.", e.Domain, addrs[0].IP, public),+ fmt.Sprintf("Change its A record to %s, then run rexctl doctor.", public))+}++func pointsHere(addrs []net.IPAddr, public string) bool {+ pub := net.ParseIP(public)+ local := map[string]bool{}+ if ifaces, err := net.InterfaceAddrs(); err == nil {+ for _, a := range ifaces {+ if n, ok := a.(*net.IPNet); ok && !n.IP.IsLoopback() && !n.IP.IsPrivate() && !n.IP.IsLinkLocalUnicast() {+ local[n.IP.String()] = true+ }+ }+ }+ for _, a := range addrs {+ if pub != nil && a.IP.Equal(pub) {+ return true+ }+ if local[a.IP.String()] {+ return true+ }+ }+ return false+}diff --git a/fluxer_rexctl/internal/checks/health.go b/fluxer_rexctl/internal/checks/health.gonew file mode 100644index 000000000..915518bc7--- /dev/null+++ b/fluxer_rexctl/internal/checks/health.go@@ -0,0 +1,101 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "crypto/tls"+ "net"+ "net/http"+ "slices"+ "strings"+ "time"+)++func init() {+ Register(Check{ID: "health", Phases: Installed, Run: runHealth})+}++func (e *Env) localAddr(key, def string) string {+ v := e.value(key)+ if v == "" {+ v = def+ }+ return localHostPort(v)+}++func localHostPort(v string) string {+ host, port, err := net.SplitHostPort(v)+ if err != nil {+ host, port = "", strings.TrimPrefix(v, ":")+ }+ if host == "" || host == "0.0.0.0" || host == "::" || host == "[::]" {+ host = "127.0.0.1"+ }+ return net.JoinHostPort(host, port)+}++func (e *Env) healthURLs() []string {+ switch e.mode() {+ case modeProxy:+ return []string{"http://" + localHostPort(e.Bind) + "/_health"}+ case modeTunnel:+ return []string{"http://" + e.localAddr("FLUXER_HTTP_PORT", "127.0.0.1:80") + "/_health"}+ }+ if strings.EqualFold(e.value("FLUXER_PUBLIC_SCHEME"), "http") {+ return []string{"http://" + e.localAddr("FLUXER_HTTP_PORT", "80") + "/_health"}+ }+ return []string{+ "https://" + e.localAddr("FLUXER_HTTPS_PORT", "443") + "/_health",+ "http://" + e.localAddr("FLUXER_HTTP_PORT", "80") + "/_health",+ }+}++func (e *Env) localClient() *http.Client {+ return &http.Client{+ Timeout: 10 * time.Second,+ Transport: &http.Transport{+ Proxy: nil,+ TLSClientConfig: &tls.Config{ServerName: e.Domain, InsecureSkipVerify: true},+ },+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },+ }+}++func runHealth(ctx context.Context, e *Env) Result {+ if e.Instance == nil {+ return skip("")+ }+ states, err := e.serviceStates(ctx)+ if err != nil || !slices.ContainsFunc(states, func(s ServiceState) bool { return s.Name == "edge" && s.Running() }) {+ return skip("")+ }+ client := e.localClient()+ answered := false+ for _, u := range e.healthURLs() {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)+ if err != nil {+ continue+ }+ req.Host = e.Domain+ resp, err := client.Do(req)+ if err != nil {+ continue+ }+ resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ return pass("Fluxer answers on this machine.")+ }+ if strings.HasPrefix(u, "https://") {+ answered = true+ continue+ }+ if !answered && resp.StatusCode >= 300 && resp.StatusCode < 400 {+ return pass("Fluxer answers on this machine.")+ }+ }+ if answered {+ return fail("Fluxer's web server answers with an error.", "Run rexctl logs api to see why.")+ }+ return fail("Fluxer doesn't answer on this machine.", "Run rexctl logs edge to see why.")+}diff --git a/fluxer_rexctl/internal/checks/livekit.go b/fluxer_rexctl/internal/checks/livekit.gonew file mode 100644index 000000000..84eff2fa8--- /dev/null+++ b/fluxer_rexctl/internal/checks/livekit.go@@ -0,0 +1,66 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "bytes"+ "context"+ "fmt"+ "net"+ "strings"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"+)++func init() {+ Register(Check{ID: "livekit-ip", Phases: Installed, Run: runLiveKitIP, Fix: fixLiveKitIP})+}++func runLiveKitIP(ctx context.Context, e *Env) Result {+ if e.Instance == nil || !e.running(ctx, "livekit") {+ return skip("")+ }+ public, perr := e.publicAddress(ctx)+ setTo := "Run rexctl doctor --fix to set it to " + public + "."+ if perr != nil {+ setTo = "Make sure this machine can send UDP traffic to the internet, then run rexctl doctor."+ }+ nodeIP := e.value("FLUXER_LIVEKIT_NODE_IP")+ external := !strings.EqualFold(e.value("FLUXER_LIVEKIT_USE_EXTERNAL_IP"), "false")+ if !external {+ if nodeIP == "" {+ r := fail("Voice calls use an address that only works inside this machine.", setTo)+ r.Fixable = perr == nil+ return r+ }+ ip := net.ParseIP(nodeIP)+ if perr == nil && ip != nil && !ip.IsPrivate() && !ip.Equal(net.ParseIP(public)) {+ return fixable(warn(fmt.Sprintf("Voice calls use %s and this machine's public IP address is %s.", nodeIP, public),+ "Run rexctl doctor --fix to use "+public+"."))+ }+ return pass(fmt.Sprintf("Voice calls use %s.", nodeIP))+ }+ var logs bytes.Buffer+ if err := e.Project.Logs(ctx, engine.LogsOptions{Tail: 300, Stdout: &logs}, "livekit"); err != nil {+ return skip("")+ }+ if strings.Contains(strings.ToLower(logs.String()), "could not resolve external ip") {+ r := fail("Voice calls can't find this machine's public IP address.", setTo)+ r.Fixable = perr == nil+ return r+ }+ return pass("Voice calls can find this machine's public IP address.")+}++func fixLiveKitIP(ctx context.Context, e *Env) error {+ if e.state() == nil {+ return errNoProject+ }+ public, err := e.publicAddress(ctx)+ if err != nil {+ return err+ }+ e.stage(settings.VoicePublicIP, &public)+ return nil+}diff --git a/fluxer_rexctl/internal/checks/origin.go b/fluxer_rexctl/internal/checks/origin.gonew file mode 100644index 000000000..4a9e097b2--- /dev/null+++ b/fluxer_rexctl/internal/checks/origin.go@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "fmt"+ "net"+ "net/url"+ "strings"+)++const originVar = "FLUXER_PUBLIC_ORIGIN"++func init() {+ Register(Check{ID: "origin", Phases: Installed, Run: runOrigin, Fix: fixOrigin})+}++func (e *Env) derivedOrigin() string {+ scheme := strings.ToLower(e.value("FLUXER_PUBLIC_SCHEME"))+ if scheme == "" {+ scheme = "https"+ }+ port := e.value("FLUXER_PUBLIC_PORT")+ domain := strings.ToLower(e.Domain)+ if port == "" || (scheme == "https" && port == "443") || (scheme == "http" && port == "80") {+ return scheme + "://" + domain+ }+ return scheme + "://" + net.JoinHostPort(domain, port)+}++func (e *Env) composeOrigin() string {+ scheme := strings.ToLower(e.value("FLUXER_PUBLIC_SCHEME"))+ if scheme == "" {+ scheme = "https"+ }+ return scheme + "://" + strings.ToLower(e.Domain)+}++func normalOrigin(s string) string {+ u, err := url.Parse(strings.TrimSpace(s))+ if err != nil || u.Host == "" {+ return strings.TrimRight(strings.ToLower(strings.TrimSpace(s)), "/")+ }+ scheme := strings.ToLower(u.Scheme)+ host := strings.ToLower(u.Hostname())+ port := u.Port()+ if port == "" || (scheme == "https" && port == "443") || (scheme == "http" && port == "80") {+ return scheme + "://" + host+ }+ return scheme + "://" + net.JoinHostPort(host, port)+}++func runOrigin(ctx context.Context, e *Env) Result {+ if e.Instance == nil || e.Domain == "" {+ return skip("")+ }+ httpPort, httpsPort := e.value("FLUXER_HTTP_PORT"), e.value("FLUXER_HTTPS_PORT")+ if httpPort == "" {+ httpPort = "80"+ }+ if httpsPort == "" {+ httpsPort = "443"+ }+ if e.mode() == modeBundled && bindPort(httpPort) == bindPort(httpsPort) {+ return fail(fmt.Sprintf("Fluxer is set to use port %s for both HTTP and HTTPS.", httpsPort),+ "Pick another HTTP port with rexctl config set edge.http_port <port>.")+ }+ want := e.derivedOrigin()+ have := e.value("FLUXER_PUBLIC_ORIGIN")+ switch {+ case strings.Contains(have, "${"):+ return fixable(warn("Your instance's public address refers to another setting.",+ fmt.Sprintf("Run rexctl doctor --fix to write it out as %s.", want)))+ case have != "" && normalOrigin(have) != want:+ return fixable(fail(fmt.Sprintf("Your instance's public address %s doesn't match %s.", strings.TrimRight(have, "/"), want),+ fmt.Sprintf("Run rexctl doctor --fix to use %s everywhere.", want)))+ case have == "" && want != e.composeOrigin():+ return fixable(fail(fmt.Sprintf("Some Fluxer services leave out the port in %s.", want),+ fmt.Sprintf("Run rexctl doctor --fix to use %s everywhere.", want)))+ }+ return pass(fmt.Sprintf("Your instance's address is %s everywhere.", want))+}++func fixOrigin(ctx context.Context, e *Env) error {+ if e.state() == nil {+ return errNoProject+ }+ if _, raw := e.state().Settings[originVar]; raw {+ e.stage(originVar, nil)+ if normalOrigin(e.value(originVar)) == e.derivedOrigin() {+ return nil+ }+ }+ want := e.derivedOrigin()+ e.stage(originVar, &want)+ return nil+}