hscontrol: serve v1 API via ogen, replace grpc-gateway facade

Mount the ogen-generated server at /api/v1 with bearer-auth and RFC 7807
errors backed by the state layer; gRPC servers stay for the CLI. Add a
servertest API client harness and Health parity tests.
This commit is contained in:
Kristoffer Dalby committed 2026-06-19 05:57:03 +00:00
1 parent 01dcd4011e
commit 562fcc1401
7 files changed
+374 -31

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
package apiv1
import (
"context"
"net/http"
oas "github.com/juanfont/headscale/gen/api/v1"
)
// HandleBearerAuth validates the API key bearer token against the state layer.
// A missing or malformed Authorization header is reported by ogen before this
// is reached. Any validation failure — a malformed/unknown key (which
// [state.State.ValidateAPIKey] reports as an error) or an expired/invalid one —
// is a 401, matching the previous middleware which rejected every such case
// with Unauthorized.
func (s *Server) HandleBearerAuth(
ctx context.Context,
_ oas.OperationName,
t oas.BearerAuth,
) (context.Context, error) {
valid, err := s.state.ValidateAPIKey(t.Token)
if err != nil || !valid {
return ctx, apiError(http.StatusUnauthorized, "invalid API key")
}
return ctx, nil
}
+143
View File
@@ -0,0 +1,143 @@
package apiv1
import (
"context"
"encoding/json"
"errors"
"net/http"
oas "github.com/juanfont/headscale/gen/api/v1"
"github.com/juanfont/headscale/hscontrol/state"
"github.com/juanfont/headscale/hscontrol/types"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)
const problemContentType = "application/problem+json"
// apiError builds an RFC 7807 problem response with the given HTTP status and
// detail. Handlers return it so expected errors render as problem documents
// with the correct status code (ogen encodes [oas.ErrorStatusCode] directly,
// without going through [errorHandler]).
func apiError(status int, detail string) *oas.ErrorStatusCode {
return &oas.ErrorStatusCode{
StatusCode: status,
Response: oas.Problem{
Title: oas.NewOptString(http.StatusText(status)),
//nolint:gosec // G115: status is an HTTP status code, always within int32.
Status: oas.NewOptInt32(int32(status)),
Detail: oas.NewOptString(detail),
},
}
}
func notFound(
detail string,
) *oas.ErrorStatusCode {
return apiError(http.StatusNotFound, detail)
}
func badRequest(
detail string,
) *oas.ErrorStatusCode {
return apiError(http.StatusBadRequest, detail)
}
func internalError(detail string) *oas.ErrorStatusCode {
return apiError(http.StatusInternalServerError, detail)
}
// mapStateError classifies an error returned by the state layer into an HTTP
// problem response. Not-found sentinels become 404; everything else is a 500.
// Handlers that need a different status (e.g. validation 400) build the problem
// explicitly with [badRequest] rather than routing through here.
func mapStateError(err error) *oas.ErrorStatusCode {
switch {
case errors.Is(err, gorm.ErrRecordNotFound),
errors.Is(err, state.ErrNodeNotFound):
return notFound(err.Error())
case errors.Is(err, types.ErrPolicyUpdateIsDisabled):
return badRequest(err.Error())
default:
return internalError(err.Error())
}
}
// NewError converts an error that ogen raises outside a handler return value —
// failed authentication, request decoding — into a typed problem response. ogen
// calls it from the generated security/decoding paths; the resulting
// [oas.ErrorStatusCode] is then encoded as application/problem+json.
func (s *Server) NewError(_ context.Context, err error) *oas.ErrorStatusCode {
return classify(err)
}
// errorHandler renders problems for the remaining ogen error path: a plain
// error returned from a handler. Expected errors are returned as
// [oas.ErrorStatusCode] (encoded directly by ogen), so this is the safety net
// for anything else.
func errorHandler(
_ context.Context,
w http.ResponseWriter,
_ *http.Request,
err error,
) {
writeProblem(w, classify(err))
}
// classify maps an arbitrary error to a problem response. An already-typed
// [oas.ErrorStatusCode] passes through; ogen's framework errors carry their own
// HTTP status via Code() (security -> 401, decode -> 400); everything else is
// classified by [mapStateError].
func classify(err error) *oas.ErrorStatusCode {
var esc *oas.ErrorStatusCode
if errors.As(err, &esc) {
return esc
}
var coder interface{ Code() int }
if errors.As(err, &coder) {
return apiError(coder.Code(), err.Error())
}
return mapStateError(err)
}
func writeProblem(w http.ResponseWriter, esc *oas.ErrorStatusCode) {
w.Header().Set("Content-Type", problemContentType)
w.WriteHeader(esc.StatusCode)
p := esc.Response
status := esc.StatusCode
if v, ok := p.Status.Get(); ok {
status = int(v)
}
body := problemJSON{
Title: p.Title.Or(""),
Status: status,
Detail: p.Detail.Or(""),
}
if v, ok := p.Type.Get(); ok {
body.Type = v.String()
}
if v, ok := p.Instance.Get(); ok {
body.Instance = v.String()
}
err := json.NewEncoder(w).Encode(body)
if err != nil {
log.Error().Err(err).Msg("writing problem response failed")
}
}
// problemJSON mirrors [oas.Problem] for hand-written encoding in
// [errorHandler]; ogen's own encoder is package-private.
type problemJSON struct {
Type string `json:"type,omitempty"`
Title string `json:"title,omitempty"`
Status int `json:"status,omitempty"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
}
+19
View File
@@ -0,0 +1,19 @@
package apiv1
import (
"context"
oas "github.com/juanfont/headscale/gen/api/v1"
)
// Health reports server health, including database connectivity. A failed
// database ping is a 500; the gRPC implementation likewise returned the ping
// error (the body's databaseConnectivity flag was never observable on failure).
func (s *Server) Health(ctx context.Context) (*oas.HealthOK, error) {
err := s.state.PingDB(ctx)
if err != nil {
return nil, internalError("pinging database: " + err.Error())
}
return &oas.HealthOK{DatabaseConnectivity: oas.NewOptBool(true)}, nil
}
+53
View File
@@ -0,0 +1,53 @@
// Package apiv1 implements the Headscale v1 HTTP API: thin handlers that
// adapt the ogen-generated server interface ([oas.Handler]) onto the shared
// state layer ([state.State]). Business logic lives in the state layer; these
// handlers only translate between HTTP request/response types and state calls.
//
// The package deliberately does not import the parent hscontrol package: it
// depends only on state, types, and the generated API package, so that
// hscontrol can mount it without an import cycle.
package apiv1
import (
"net/http"
oas "github.com/juanfont/headscale/gen/api/v1"
"github.com/juanfont/headscale/hscontrol/state"
"github.com/juanfont/headscale/hscontrol/types"
"github.com/juanfont/headscale/hscontrol/types/change"
)
// Server implements the generated [oas.Handler] and [oas.SecurityHandler].
//
// Operations that have not been migrated from the gRPC stack yet are inherited
// from [oas.UnimplementedHandler] and return 501; each resource group replaces
// its stubs as it is converted.
type Server struct {
oas.UnimplementedHandler
state *state.State
cfg *types.Config
change changeFunc
}
// changeFunc distributes state changes to connected nodes. In production this
// is [github.com/juanfont/headscale/hscontrol.Headscale.Change]; tests may pass
// a no-op or a recorder.
type changeFunc func(...change.Change)
// NewHandler builds the v1 API as an [http.Handler] ready to mount at
// /api/v1. changeFn distributes [change.Change]s produced by mutating
// operations; it must not be nil (pass a no-op if changes are irrelevant).
func NewHandler(
st *state.State,
cfg *types.Config,
changeFn func(...change.Change),
) (http.Handler, error) {
s := &Server{
state: st,
cfg: cfg,
change: changeFn,
}
return oas.NewServer(s, s, oas.WithErrorHandler(errorHandler))
}