Files

109 lines
3.6 KiB
Go

package server
import (
"context"
"crypto/sha256"
"crypto/subtle"
"errors"
"fmt"
"log/slog"
"net/http"
"time"
"lincodex/runner/internal/api"
)
var errInvalidToken = errors.New("invalid bearer token")
// tokenAuth checks the shared service token. Comparing SHA-256 digests in
// constant time hides both the content and the length of the token.
type tokenAuth struct {
digest [sha256.Size]byte
}
func (a tokenAuth) HandleBearerAuth(ctx context.Context, _ api.OperationName, token api.BearerAuth) (context.Context, error) {
digest := sha256.Sum256([]byte(token.Token))
if subtle.ConstantTimeCompare(digest[:], a.digest[:]) != 1 {
return ctx, errInvalidToken
}
return ctx, nil
}
// New returns the HTTP handler of the runner API.
func New(handler *Handler, token string, maxRequestBytes int64, logger *slog.Logger) (http.Handler, error) {
if token == "" {
return nil, errors.New("server.New - empty service token")
}
generated, err := api.NewServer(handler, tokenAuth{digest: sha256.Sum256([]byte(token))},
api.WithErrorHandler(errorHandler(logger)),
api.WithNotFound(func(w http.ResponseWriter, _ *http.Request) {
writeProblem(w, newProblem(http.StatusNotFound, api.ProblemCodeNotFound, "The route does not exist."))
}),
api.WithMethodNotAllowed(func(w http.ResponseWriter, _ *http.Request, allowed string) {
w.Header().Set("Allow", allowed)
writeProblem(w, newProblem(http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, "The route does not support this method."))
}),
)
if err != nil {
return nil, fmt.Errorf("server.New - generated server: %w", err)
}
return accessLog(generated, logger, recoverPanics(logger, limitBody(maxRequestBytes, generated))), nil
}
// limitBody refuses bodies above the limit before they are read.
func limitBody(limit int64, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength > limit {
writeProblem(w, newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit."))
return
}
r.Body = http.MaxBytesReader(w, r.Body, limit)
next.ServeHTTP(w, r)
})
}
func recoverPanics(logger *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
defer func() {
if recovered := recover(); recovered != nil {
// The panic value may hold request data; only its type is logged.
logger.ErrorContext(ctx, "request panicked", slog.String("panic_type", fmt.Sprintf("%T", recovered)))
writeProblem(w, newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request."))
}
}()
next.ServeHTTP(w, r)
})
}
// accessLog writes one line per request with the operation, status, and
// duration. Bodies, headers, and query strings are never logged.
func accessLog(router *api.Server, logger *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(recorder, r)
operation := "unknown"
if route, ok := router.FindPath(r.Method, r.URL); ok {
operation = route.OperationID()
}
logger.InfoContext(r.Context(), "request",
slog.String("method", r.Method),
slog.String("operation", operation),
slog.Int("status", recorder.status),
slog.Int64("duration_ms", time.Since(started).Milliseconds()),
)
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}