175 lines
6.0 KiB
Go
175 lines
6.0 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/netip"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"lincodex/labd/internal/api"
|
|
)
|
|
|
|
var (
|
|
errInvalidToken = errors.New("invalid bearer token")
|
|
// consoleAttachPath is the planned WebSocket attach of a console token.
|
|
consoleAttachPath = regexp.MustCompile(`^/v1/labs/[^/]+/console$`)
|
|
)
|
|
|
|
// 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) {
|
|
if !a.valid(token.Token) {
|
|
return ctx, errInvalidToken
|
|
}
|
|
return ctx, nil
|
|
}
|
|
|
|
func (a tokenAuth) valid(token string) bool {
|
|
digest := sha256.Sum256([]byte(token))
|
|
return subtle.ConstantTimeCompare(digest[:], a.digest[:]) == 1
|
|
}
|
|
|
|
// Options configure the HTTP handler.
|
|
type Options struct {
|
|
Token string
|
|
MaxRequestBytes int64
|
|
// AllowedClients are the networks requests may come from.
|
|
AllowedClients []netip.Prefix
|
|
}
|
|
|
|
// New returns the HTTP handler of the labd API.
|
|
func New(handler *Handler, options Options, logger *slog.Logger) (http.Handler, error) {
|
|
if options.Token == "" {
|
|
return nil, errors.New("server.New - empty service token")
|
|
}
|
|
if len(options.AllowedClients) == 0 {
|
|
return nil, errors.New("server.New - no allowed client network")
|
|
}
|
|
auth := tokenAuth{digest: sha256.Sum256([]byte(options.Token))}
|
|
generated, err := api.NewServer(handler, auth,
|
|
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)
|
|
}
|
|
routes := consoleAttach(auth, limitBody(options.MaxRequestBytes, generated))
|
|
return accessLog(generated, logger, recoverPanics(logger, allowClients(options.AllowedClients, logger, routes))), nil
|
|
}
|
|
|
|
// allowClients refuses requests from outside the allowed networks before
|
|
// any other check, as if the token were wrong, so the answer tells such a
|
|
// caller nothing.
|
|
func allowClients(allowed []netip.Prefix, logger *slog.Logger, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
address, err := netip.ParseAddrPort(r.RemoteAddr)
|
|
if err != nil || !contains(allowed, address.Addr().Unmap()) {
|
|
logger.WarnContext(r.Context(), "request from a network outside LABD_ALLOWED_CLIENTS refused", slog.String("remote", r.RemoteAddr))
|
|
writeProblem(w, newProblem(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token."))
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func contains(prefixes []netip.Prefix, address netip.Addr) bool {
|
|
for _, prefix := range prefixes {
|
|
if prefix.Contains(address) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// consoleAttach answers the planned WebSocket attach of a console token. It
|
|
// checks the service token like every operation and then reports the attach
|
|
// as not implemented.
|
|
func consoleAttach(auth tokenAuth, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if !consoleAttachPath.MatchString(r.URL.Path) {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
token, found := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
if !found || !auth.valid(token) {
|
|
writeProblem(w, newProblem(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token."))
|
|
return
|
|
}
|
|
writeProblem(w, newProblem(http.StatusNotImplemented, api.ProblemCodeNotImplemented, "The console attach is not implemented yet."))
|
|
})
|
|
}
|
|
|
|
// 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)
|
|
}
|