Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 52 additions & 13 deletions cmd/tinyauth/healthcheck.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package main

import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"time"

"github.com/tinyauthapp/paerser/cli"
"github.com/tinyauthapp/tinyauth/internal/utils"
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
)

Expand All @@ -29,20 +33,15 @@ func healthcheckCmd() *cli.Command {
log := logger.NewLogger().WithSimpleConfig()
log.Init()

srvAddr := os.Getenv("TINYAUTH_SERVER_ADDRESS")
if srvAddr == "" {
srvAddr = "127.0.0.1"
}

srvPort := os.Getenv("TINYAUTH_SERVER_PORT")
if srvPort == "" {
srvPort = "3000"
}

appUrl := fmt.Sprintf("http://%s:%s", srvAddr, srvPort)
appUrl, socketPath := healthcheckTarget(
os.Getenv("TINYAUTH_SERVER_ADDRESS"),
os.Getenv("TINYAUTH_SERVER_PORT"),
os.Getenv("TINYAUTH_SERVER_SOCKETPATH"),
)

if len(args) > 0 {
appUrl = args[0]
socketPath = ""
}

if appUrl == "" {
Expand All @@ -55,6 +54,16 @@ func healthcheckCmd() *cli.Command {
Timeout: 30 * time.Second,
}

if socketPath != "" {
log.App.Info().Str("socket_path", socketPath).Msg("Using unix socket")
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil
transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "unix", socketPath)
}
client.Transport = transport
}

req, err := http.NewRequest("GET", appUrl+"/api/healthz", nil)

if err != nil {
Expand All @@ -67,12 +76,12 @@ func healthcheckCmd() *cli.Command {
return fmt.Errorf("failed to perform request: %w", err)
}

defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("service is not healthy, got: %s", resp.Status)
}

defer resp.Body.Close()

var healthResp healthzResponse

body, err := io.ReadAll(resp.Body)
Expand All @@ -93,3 +102,33 @@ func healthcheckCmd() *cli.Command {
},
}
}

// healthcheckTarget returns the URL to probe and, when tinyauth serves on a unix socket, the socket to dial.
// Wildcard listen addresses are probed on IPv4 loopback.
func healthcheckTarget(addr string, port string, socketPath string) (string, string) {
if socketPath != "" {
return "http://tinyauth", socketPath
}

host := utils.TrimHostBrackets(addr)
switch host {
case "", "0.0.0.0":
// IPv4 wildcard (and the dual-stack :port listener): IPv4 loopback reaches it.
host = "127.0.0.1"
case "::":
// IPv6 wildcard: probe IPv6 loopback. It reaches a [::] listener whether it is
// dual-stack or IPv6-only, whereas 127.0.0.1 fails on an IPv6-only listener
// (a platform without IPv4-mapped IPv6, e.g. bindv6only).
host = "::1"
}

if port == "" {
port = "3000"
}

// A link-local address keeps its zone id (fe80::1%eth0); the listener accepts the raw
// %, but it must be percent-encoded as %25 before it goes into the probe URL host.
host = strings.ReplaceAll(host, "%", "%25")

return "http://" + utils.JoinHostPort(host, port), ""
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
31 changes: 31 additions & 0 deletions cmd/tinyauth/healthcheck_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestHealthcheckTarget(t *testing.T) {
tests := []struct {
addr, port, socket string
url, socketPath string
}{
{"", "", "", "http://127.0.0.1:3000", ""},
{"0.0.0.0", "3003", "", "http://127.0.0.1:3003", ""},
{"::", "3000", "", "http://[::1]:3000", ""},
{"[::]", "3000", "", "http://[::1]:3000", ""},
{"::1", "3000", "", "http://[::1]:3000", ""},
{"fe80::1%eth0", "3000", "", "http://[fe80::1%25eth0]:3000", ""},
{"[fe80::1%eth0]", "3000", "", "http://[fe80::1%25eth0]:3000", ""},
{"192.0.2.10", "", "", "http://192.0.2.10:3000", ""},
{"tinyauth", "8080", "", "http://tinyauth:8080", ""},
{"0.0.0.0", "3000", "/run/tinyauth.sock", "http://tinyauth", "/run/tinyauth.sock"},
}

for _, tt := range tests {
url, socketPath := healthcheckTarget(tt.addr, tt.port, tt.socket)
assert.Equal(t, tt.url, url, "addr=%q port=%q socket=%q", tt.addr, tt.port, tt.socket)
assert.Equal(t, tt.socketPath, socketPath, "addr=%q port=%q socket=%q", tt.addr, tt.port, tt.socket)
}
}
3 changes: 2 additions & 1 deletion internal/bootstrap/router_bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/tinyauthapp/tinyauth/internal/controller"
"github.com/tinyauthapp/tinyauth/internal/middleware"
"github.com/tinyauthapp/tinyauth/internal/model"
"github.com/tinyauthapp/tinyauth/internal/utils"
"go.uber.org/dig"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -147,7 +148,7 @@ func (app *BootstrapApp) getListenerFunc() (func(ctx context.Context) error, err
}

func (app *BootstrapApp) serveHTTP(ctx context.Context) error {
address := fmt.Sprintf("%s:%d", app.config.Server.Address, app.config.Server.Port)
address := utils.JoinHostPort(app.config.Server.Address, fmt.Sprint(app.config.Server.Port))

app.log.App.Info().Msgf("Starting server on http://%s", address)

Expand Down
13 changes: 13 additions & 0 deletions internal/utils/app_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,16 @@ func Filter[T any](slice []T, test func(T) bool) (res []T) {
}
return res
}

// JoinHostPort joins a host and port, bracketing IPv6 addresses. Already bracketed hosts (e.g. [::]) are accepted too.
func JoinHostPort(host string, port string) string {
return net.JoinHostPort(TrimHostBrackets(host), port)
}

// TrimHostBrackets removes one pair of enclosing brackets (e.g. [::] becomes ::), unbalanced brackets are kept so they still fail to parse
func TrimHostBrackets(host string) string {
if len(host) >= 2 && host[0] == '[' && host[len(host)-1] == ']' {
return host[1 : len(host)-1]
}
return host
}
15 changes: 15 additions & 0 deletions internal/utils/app_utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,18 @@ func TestFilter(t *testing.T) {
resultStr := utils.Filter(sliceStr, testFuncStr)
assert.Equal(t, expectedStr, resultStr)
}

func TestJoinHostPort(t *testing.T) {
assert.Equal(t, "0.0.0.0:3000", utils.JoinHostPort("0.0.0.0", "3000"))
assert.Equal(t, "[::]:3000", utils.JoinHostPort("::", "3000"))
assert.Equal(t, "[::]:3000", utils.JoinHostPort("[::]", "3000"))
assert.Equal(t, "[::1]:3000", utils.JoinHostPort("::1", "3000"))
assert.Equal(t, "[fe80::1%eth0]:3000", utils.JoinHostPort("fe80::1%eth0", "3000"))
assert.Equal(t, "localhost:3000", utils.JoinHostPort("localhost", "3000"))
assert.Equal(t, ":3000", utils.JoinHostPort("", "3000"))

// Unbalanced brackets are not stripped, so listening on them still fails
assert.Equal(t, "[::]]:3000", utils.JoinHostPort("::]", "3000"))
assert.Equal(t, "[[::]:3000", utils.JoinHostPort("[::", "3000"))
assert.Equal(t, "[127.0.0.1:3000", utils.JoinHostPort("[127.0.0.1", "3000"))
}