Skip to content
Merged
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
3 changes: 3 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,7 @@ COPY --from=build /proxy /proxy

USER 65534:65534

HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD ["/proxy", "healthcheck"]

ENTRYPOINT ["/proxy"]
4 changes: 2 additions & 2 deletions IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,8 @@ Each item follows TDD: write failing test first, then implement, then refactor.

### 8. Health check endpoint

- [ ] **`GET /healthz`**: Returns `200 OK` when the server is ready to accept requests. No authentication, no IP check — intended for container orchestrators.
- [ ] **Dockerfile `HEALTHCHECK`**: Use the binary itself (e.g. subcommand or dedicated flag) to probe `/healthz`, since `scratch` has no shell or curl.
- [x] **`GET /healthz`**: Returns `200 OK` when the server is ready to accept requests. No authentication, no IP check — intended for container orchestrators.
- [x] **Dockerfile `HEALTHCHECK`**: Use the binary itself (e.g. subcommand or dedicated flag) to probe `/healthz`, since `scratch` has no shell or curl.

### 9. End-to-end test

Expand Down
25 changes: 25 additions & 0 deletions cmd/proxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ import (
const githubMetaURL = "https://api.github.com/meta"

func main() {
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
os.Exit(healthcheck())
}

Comment thread
strayer marked this conversation as resolved.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

Expand All @@ -39,6 +43,27 @@ func main() {
}
}

func healthcheck() int {
addr := os.Getenv("LISTEN_ADDR")
if addr == "" {
addr = ":8080"
}
_, port, err := net.SplitHostPort(addr)
if err != nil {
return 1
}
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get("http://localhost:" + port + "/healthz")
Comment thread
strayer marked this conversation as resolved.
Comment thread
strayer marked this conversation as resolved.
if err != nil {
Comment thread
strayer marked this conversation as resolved.
return 1
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return 1
}
return 0
}

func run(ctx context.Context, cfg *proxy.Config, metaURL string, ln net.Listener) error {
checker, err := proxy.NewGitHubIPChecker(metaURL, cfg.GitHubMetaRefreshInterval)
if err != nil {
Expand Down
67 changes: 67 additions & 0 deletions cmd/proxy/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,73 @@ func TestRun_RejectsWrongMethod(t *testing.T) {
<-errCh
}

func TestHealthcheck_Success(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/healthz" {
t.Errorf("expected path /healthz, got %s", r.URL.Path)
}
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()

_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
t.Setenv("LISTEN_ADDR", ":"+port)

if code := healthcheck(); code != 0 {
t.Errorf("expected exit code 0, got %d", code)
}
}

func TestHealthcheck_DefaultAddr(t *testing.T) {
t.Setenv("LISTEN_ADDR", "")

ln, err := net.Listen("tcp", "127.0.0.1:8080")
if err != nil {
t.Skip("port 8080 unavailable")
}
srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})}
go func() { _ = srv.Serve(ln) }()
defer func() { _ = srv.Close() }()

Comment thread
strayer marked this conversation as resolved.
waitForServer(t, "127.0.0.1:8080")

if code := healthcheck(); code != 0 {
t.Errorf("expected exit code 0, got %d", code)
}
}

func TestHealthcheck_Unreachable(t *testing.T) {
t.Setenv("LISTEN_ADDR", ":19999")

if code := healthcheck(); code != 1 {
t.Errorf("expected exit code 1, got %d", code)
}
}

func TestHealthcheck_Non200(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}))
defer srv.Close()

_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
t.Setenv("LISTEN_ADDR", ":"+port)

if code := healthcheck(); code != 1 {
t.Errorf("expected exit code 1, got %d", code)
}
}

func TestHealthcheck_InvalidAddr(t *testing.T) {
t.Setenv("LISTEN_ADDR", "not-a-valid-addr")

if code := healthcheck(); code != 1 {
t.Errorf("expected exit code 1, got %d", code)
}
}

func waitForServer(t *testing.T, addr string) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
Expand Down
7 changes: 7 additions & 0 deletions internal/proxy/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ func NewHandler(cfg *Config, checker *GitHubIPChecker, forwarder *Forwarder) htt
checker: checker,
forwarder: forwarder,
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
slog.Info("request to unregistered path", "path", r.URL.Path, "method", r.Method)
w.WriteHeader(http.StatusNotFound)
Expand Down
47 changes: 47 additions & 0 deletions internal/proxy/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,53 @@ func TestHandler_RepoAllowlistCaseInsensitive(t *testing.T) {
}
}

func TestHandler_HealthzGET(t *testing.T) {
backend := failingBackend(t)
defer backend.Close()
h := NewHandler(testConfig(backend.URL), testChecker(t, "127.0.0.0/8"), NewForwarder())

req := httptest.NewRequest("GET", "/healthz", nil)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)

if rr.Code != http.StatusOK {
t.Errorf("expected %d, got %d", http.StatusOK, rr.Code)
}
}

func TestHandler_HealthzNoAuth(t *testing.T) {
backend := failingBackend(t)
defer backend.Close()
h := NewHandler(testConfig(backend.URL), testChecker(t, "192.0.2.0/24"), NewForwarder())

req := httptest.NewRequest("GET", "/healthz", nil)
req.RemoteAddr = "10.0.0.1:12345"
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)

if rr.Code != http.StatusOK {
t.Errorf("healthz should not check IP, expected %d, got %d", http.StatusOK, rr.Code)
}
}

func TestHandler_HealthzRejectsNonGET(t *testing.T) {
backend := failingBackend(t)
defer backend.Close()
h := NewHandler(testConfig(backend.URL), testChecker(t, "127.0.0.0/8"), NewForwarder())

methods := []string{"POST", "PUT", "DELETE", "PATCH"}
for _, m := range methods {
t.Run(m, func(t *testing.T) {
req := httptest.NewRequest(m, "/healthz", nil)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
if rr.Code != http.StatusMethodNotAllowed {
t.Errorf("expected %d for %s, got %d", http.StatusMethodNotAllowed, m, rr.Code)
}
})
}
}

func TestHandler_DoesNotForwardResponseBody(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Internal", "secret-info")
Expand Down