feat: scaffold project with config, store, health endpoint, CI, and Dockerfile

Phase 1 of foreman: initialize the Go module, project layout, and core
infrastructure. Includes env-based configuration (FOREMAN_* namespace),
SQLite-backed durable job queue with WAL mode via modernc.org/sqlite,
stdlib HTTP server with /healthz and optional bearer-token auth middleware,
subcommand dispatch (serve + stubs), Gitea CI workflow, multi-stage
distroless Dockerfile, and comprehensive tests for all packages.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-23 17:58:36 -04:00
parent d5702f7a75
commit 9cdf4b2472
15 changed files with 1474 additions and 0 deletions
+117
View File
@@ -0,0 +1,117 @@
// Package server provides the HTTP API for the foreman daemon.
//
// Why: foreman exposes a native Ollama-compatible API plus async job endpoints;
// centralizing routing and middleware here keeps cmd/foreman thin.
// What: creates a stdlib net/http server with health checks, optional bearer-token
// auth, and an extensible mux for later phases.
// Test: start the server with httptest, hit /healthz, verify 200; set a token,
// verify 401 without it.
package server
import (
"encoding/json"
"log/slog"
"net/http"
"strings"
"gitea.stevedudenhoeffer.com/steve/foreman/internal/config"
"gitea.stevedudenhoeffer.com/steve/foreman/internal/store"
)
// Server holds the HTTP server and its dependencies.
type Server struct {
cfg config.Config
store *store.Store
mux *http.ServeMux
logger *slog.Logger
}
// New creates a new Server with the given configuration and store. The mux is
// populated with initial routes; callers can add more before calling ListenAndServe.
//
// Why: dependency injection makes the server testable and extensible.
// What: wires config, store, and logger into the server, registers routes.
// Test: create with New, use httptest to exercise routes.
func New(cfg config.Config, st *store.Store, logger *slog.Logger) *Server {
s := &Server{
cfg: cfg,
store: st,
mux: http.NewServeMux(),
logger: logger,
}
s.routes()
return s
}
// Handler returns the server's http.Handler, with auth middleware applied.
//
// Why: allows httptest usage in tests without starting a real listener.
// What: wraps the mux with optional bearer-token middleware.
// Test: call Handler(), use httptest.NewServer, exercise endpoints.
func (s *Server) Handler() http.Handler {
var h http.Handler = s.mux
if s.cfg.Token != "" {
h = s.authMiddleware(h)
}
return h
}
// ListenAndServe starts the HTTP server on the configured address.
func (s *Server) ListenAndServe() error {
s.logger.Info("starting server", "addr", s.cfg.Addr)
return http.ListenAndServe(s.cfg.Addr, s.Handler())
}
// routes registers all HTTP routes on the mux.
func (s *Server) routes() {
s.mux.HandleFunc("GET /healthz", s.handleHealthz)
}
// healthResponse is the JSON shape returned by /healthz.
type healthResponse struct {
Status string `json:"status"`
Degraded bool `json:"degraded"`
}
// handleHealthz returns the daemon's health status. The degraded flag is a
// placeholder for the model poller's connectivity state (Phase 2).
func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(healthResponse{
Status: "ok",
Degraded: false,
})
}
// authMiddleware validates the Authorization: Bearer <token> header on all
// requests except /healthz. Returns 401 if the token is missing or wrong.
func (s *Server) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// /healthz is always public so load balancers and probes work without auth.
if r.URL.Path == "/healthz" {
next.ServeHTTP(w, r)
return
}
auth := r.Header.Get("Authorization")
if auth == "" {
http.Error(w, `{"error":"missing authorization header"}`, http.StatusUnauthorized)
return
}
const prefix = "Bearer "
if !strings.HasPrefix(auth, prefix) {
http.Error(w, `{"error":"invalid authorization header"}`, http.StatusUnauthorized)
return
}
token := strings.TrimPrefix(auth, prefix)
if token != s.cfg.Token {
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
+140
View File
@@ -0,0 +1,140 @@
package server
import (
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"gitea.stevedudenhoeffer.com/steve/foreman/internal/config"
"gitea.stevedudenhoeffer.com/steve/foreman/internal/store"
)
// newTestServer creates a Server backed by a temp-dir SQLite store.
func newTestServer(t *testing.T, cfg config.Config) *Server {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
st, err := store.Open(dbPath)
if err != nil {
t.Fatalf("store.Open: %v", err)
}
t.Cleanup(func() { st.Close() })
logger := slog.Default()
return New(cfg, st, logger)
}
func TestHealthz_OK(t *testing.T) {
srv := newTestServer(t, config.Config{
OllamaURL: "http://localhost:11434",
})
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
var resp healthResponse
if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
t.Fatalf("decode response: %v", err)
}
if resp.Status != "ok" {
t.Errorf("status = %q, want %q", resp.Status, "ok")
}
if resp.Degraded {
t.Error("degraded should be false")
}
}
func TestHealthz_NoAuthRequired(t *testing.T) {
srv := newTestServer(t, config.Config{
OllamaURL: "http://localhost:11434",
Token: "secret-token",
})
// /healthz should work without any auth header even when token is configured.
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want %d (healthz should bypass auth)", rec.Code, http.StatusOK)
}
}
func TestAuth_RequiredWhenTokenSet(t *testing.T) {
srv := newTestServer(t, config.Config{
OllamaURL: "http://localhost:11434",
Token: "secret-token",
})
tests := []struct {
name string
path string
auth string
want int
}{
{
name: "no auth header",
path: "/some-route",
auth: "",
want: http.StatusUnauthorized,
},
{
name: "wrong token",
path: "/some-route",
auth: "Bearer wrong-token",
want: http.StatusUnauthorized,
},
{
name: "correct token",
path: "/some-route",
auth: "Bearer secret-token",
// Route doesn't exist so we get 404, but auth passed.
want: http.StatusNotFound,
},
{
name: "invalid scheme",
path: "/some-route",
auth: "Basic dXNlcjpwYXNz",
want: http.StatusUnauthorized,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
if tt.auth != "" {
req.Header.Set("Authorization", tt.auth)
}
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Errorf("status = %d, want %d", rec.Code, tt.want)
}
})
}
}
func TestAuth_NotRequiredWhenNoToken(t *testing.T) {
srv := newTestServer(t, config.Config{
OllamaURL: "http://localhost:11434",
// Token intentionally empty.
})
// Without a configured token, any request should pass auth (even to a
// nonexistent route, which returns 404 rather than 401).
req := httptest.NewRequest(http.MethodGet, "/some-route", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code == http.StatusUnauthorized {
t.Error("should not require auth when no token is configured")
}
}